<!--流程中节点的输出圆点组件-->
<template>
<!--  <div :title="item.description+' 类型：'+item.cat" class="pane-port"-->
  <div :title="item.key + ' - ' + item.description" class="pane-port"
       :class="{'data':item.cat=='DATA', 'model':item.cat=='MODEL', 'unstruct': item.cat=='UNSTRUCT'}" :id="item.id"
       :style="leftStyle" @mousedown="outMouseDown($event)">
    <span class="port-magnet"></span>
  </div>
</template>
<script>
import { switchCreateLineRelation } from "../../../../api/sourceDetail";
import { mapGetters } from "vuex";

var d3 = require("d3");
var line, w;
export default {
  name: "EleOutPortItem",
  props: ["item", "index", "nodeId"],
  data: function() {
    return {
      source: ""
    };
  },
  computed: {
    ...mapGetters(["httpServer"]),
    leftStyle: function() {
      return {
        left: this.item.left + "px"
      };
    },
    flowData: function() {
      return this.$store.state.project.flowData;
    }
  },
  methods: {
    outMouseDown: function(event) {
      if (this.$route.path !== "/home/projectTwo") {
        //输出点鼠标按下事件
        this.flowData.source = {
          sourceNodeId: this.nodeId,
          sourcePortId: this.item.id,
          key: this.item.key,
          cat: this.item.cat
        };
        var offset = event.currentTarget.getBoundingClientRect();
        var contentDomOffset = document
          .getElementById("dwaContent")
          .getBoundingClientRect();
        var source = {
          x: offset.left - contentDomOffset.left + 6,
          y: offset.top - contentDomOffset.top
        };
        this.source = source;
        var judgeClazz = this.item.cat.toLocaleLowerCase();
        var tempSelect = `.in .${judgeClazz}`;
        d3.selectAll(tempSelect).classed("is-connectable", true);
        //清除已被连接的点的可被链接状态
        d3.selectAll(".in .is-connected").classed("is-connectable", false);
        //清除自身节点的输入可被链接状态
        d3.select("#node" + this.nodeId)
          .selectAll(".in .pane-port")
          .classed("is-connectable", false);
        var position = [{ source: source, target: source }];
        line = d3
          .selectAll("svg")
          .append("g")
          .selectAll("path")
          .data(position)
          .enter()
          .append("path")
          .attr("class", "test")
          .attr("d", this.elbow);
        w = d3
          .select(window)
          .on("mousemove", this.mouseMove)
          .on("mouseup", this.mouseUp);
        event.preventDefault();
        // console.log(JSON.parse(JSON.stringify(this.flowData)));
      }
    },
    mouseMove: function() {
      //鼠标划线开始后的移动事件
      var contentDomOffset = document
        .getElementById("dwaContent")
        .getBoundingClientRect();
      var target = {
        x: d3.event.pageX - contentDomOffset.left,
        y: d3.event.pageY - contentDomOffset.top
      };
      var position = [{ source: this.source, target: target }];
      line
        .data(position)
        .transition()
        .duration(10)
        .attr("d", this.elbow);
    },
    mouseUp: function() {
      //鼠标划线结束后放开事件
      // console.log(JSON.parse(JSON.stringify(this.flowData)));
      let allNodesData = this.$store.state.project.flowData.nodes; //所有节点的集合
      // console.log(JSON.parse(JSON.stringify(allNodesData)));
      let paramsData = [
        {
          id: "",
          name: this.flowData.source.key
        },
        {
          id: "",
          name: ""
        }
      ];
      let targetAlgorithmList = [];
      allNodesData &&
        allNodesData.forEach(val => {
          if (
            this.flowData.source.sourceNodeId.toString() === val.id.toString()
          ) {
            paramsData[0].id = val.serverId;
            targetAlgorithmList.push(val.targetAlgorithm);
          }
          if (
            this.flowData.target.targetNodeId.toString() === val.id.toString()
          ) {
            paramsData[1].id = val.serverId;
            targetAlgorithmList.push(val.targetAlgorithm);
          }
          val.inputs &&
            val.inputs.forEach(ele => {
              if (
                this.flowData.target.targetPortId.toString() ===
                ele.id.toString()
              ) {
                paramsData[1].name = ele.key;
              }
            });
          val.outputs &&
            val.outputs.forEach(ele => {
              if (
                this.flowData.target.targetPortId.toString() ===
                ele.id.toString()
              ) {
                paramsData[1].name = ele.key;
              }
            });
        });
      console.log(targetAlgorithmList);
      const newD3EventPageX = JSON.parse(JSON.stringify(d3.event.pageX));
      const newD3EventPageY = JSON.parse(JSON.stringify(d3.event.pageY));

      // TODO TODO TODO
      if (
        targetAlgorithmList.indexOf(
          "com.tipdm.framework.dmserver.core.algo.unparallel.file.Parse"
        ) >= 0 ||
        targetAlgorithmList.length <= 1
      ) {
        //两个 连线的大节点有app文件转换
        //////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////////
        this.flowData.source = {
          sourceNodeId: "",
          sourcePortId: "",
          key: "",
          cat: ""
        };
        if (!this.flowData.isConnecting) {
          line.remove();
        } else {
          var dom = document.elementFromPoint(d3.event.pageX, d3.event.pageY);
          var offset = dom.getBoundingClientRect();
          var contentDomOffset = document
            .getElementById("dwaContent")
            .getBoundingClientRect();
          var target = {
            x: offset.left - contentDomOffset.left + 20,
            y: offset.top - contentDomOffset.top + 20
          };
          var position = [{ source: this.source, target: target }];
          line
            .data(position)
            .transition()
            .duration(10)
            .attr("d", this.elbow);
          line.remove();
          if (
            this.nodeId ==
            this.$store.state.project.flowData.target.targetNodeId
          ) {
            //连线时输入与输出是同一节点时不能生成连线
          } else {
            this.$store.commit("addFlowLinkNode", {
              sourceId: this.nodeId,
              d: this.elbow(position[0]),
              outputPortId: this.item.id
            });
          }
          //                d3.select(dom.parentNode).classed("is-connected", true); 该行废弃，改为通过数据更新dom
        }
        d3.selectAll(".in .pane-port").classed("is-connectable", false);
        w.on("mousemove", null).on("mouseup", null);
        //////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////////////////////////

        // console.log('有app文件转换 的节点连线时 自动保存一次');
        this.saveFlow();
        return;
      }

      //云鹏说先不校验连线 等需要的时候 删掉下面这些 打开 下面的请求的
      ////////////////////////////////////////////////////////////////////////////////////////////////
      //不校验连线--不校验连线--不校验连线--不校验连线--不校验连线--不校验连线--不校验连线--不校验连线--不校验连线--
      ////////////////////////////////////////////////////////////////////////////////////////////////
      // console.log(1111,res.message);
      this.flowData.source = {
        sourceNodeId: "",
        sourcePortId: "",
        key: "",
        cat: ""
      };
      // console.log('!this.flowData.isConnecting >>>>>> ',!this.flowData.isConnecting);
      if (!this.flowData.isConnecting) {
        line.remove();
      } else {
        // var dom = document.elementFromPoint(d3.event.pageX, d3.event.pageY);
        var dom = document.elementFromPoint(newD3EventPageX, newD3EventPageY);
        var offset = dom.getBoundingClientRect();
        var contentDomOffset = document
          .getElementById("dwaContent")
          .getBoundingClientRect();
        var target = {
          x: offset.left - contentDomOffset.left + 20,
          y: offset.top - contentDomOffset.top + 20
        };
        var position = [{ source: this.source, target: target }];
        line
          .data(position)
          .transition()
          .duration(10)
          .attr("d", this.elbow);
        line.remove();
        if (
          this.nodeId == this.$store.state.project.flowData.target.targetNodeId
        ) {
          //连线时输入与输出是同一节点时不能生成连线
        } else {
          this.$store.commit("addFlowLinkNode", {
            sourceId: this.nodeId,
            d: this.elbow(position[0]),
            outputPortId: this.item.id
          });
        }
        //d3.select(dom.parentNode).classed("is-connected", true); 该行废弃，改为通过数据更新dom
      }

      d3.selectAll(".in .pane-port").classed("is-connectable", false);
      w.on("mousemove", null).on("mouseup", null);
      ////////////////////////////////////////////////////////////////////////////////////////////////
      //不校验连线--不校验连线--不校验连线--不校验连线--不校验连线--不校验连线--不校验连线--不校验连线--不校验连线--
      ////////////////////////////////////////////////////////////////////////////////////////////////

      /*
        //【校验连线】--【校验连线】--【校验连线】--【校验连线】--【校验连线】--【校验连线】--【校验连线】--【校验连线】--
        switchCreateLineRelation(paramsData).then(res=>{
          // console.log(res);
          if(res.status === 'SUCCESS' && (res.message && res.message.toString() === 'true')){
            ////////////////////////////////////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////////////////////////////////////
            // console.log(1111,res.message);
            this.flowData.source = {
              sourceNodeId: "",
              sourcePortId: "",
              key: "",
              cat: ""
            };
            // console.log('!this.flowData.isConnecting >>>>>> ',!this.flowData.isConnecting);
            if (!this.flowData.isConnecting) {
              line.remove();
            } else {
              // var dom = document.elementFromPoint(d3.event.pageX, d3.event.pageY);
              var dom = document.elementFromPoint(newD3EventPageX,newD3EventPageY);
              var offset = dom.getBoundingClientRect();
              var contentDomOffset = document.getElementById("dwaContent").getBoundingClientRect();
              var target = {x: offset.left - contentDomOffset.left + 20, y: offset.top - contentDomOffset.top + 20};
              var position = [{source: this.source, target: target}];
              line.data(position).transition().duration(10).attr("d", this.elbow);
              line.remove();
              if (this.nodeId == this.$store.state.project.flowData.target.targetNodeId) {//连线时输入与输出是同一节点时不能生成连线
              } else {
                this.$store.commit("addFlowLinkNode", {
                  sourceId: this.nodeId,
                  d: this.elbow(position[0]),
                  outputPortId: this.item.id
                });
              }
              //d3.select(dom.parentNode).classed("is-connected", true); 该行废弃，改为通过数据更新dom
            }

            d3.selectAll(".in .pane-port").classed("is-connectable", false);
            w.on("mousemove", null).on("mouseup", null);
            ////////////////////////////////////////////////////////////////////////////////////////////////
            ////////////////////////////////////////////////////////////////////////////////////////////////

          }else{
            // console.log(222);
            line.remove();
            this.$message.warning('校验失败，这两点不可连线！');
            return
          }
        }).catch(err=>{
          // console.log(333);
          line.remove();
          this.$message.warning('连接失败！');
          return
        })
        //【校验连线】--【校验连线】--【校验连线】--【校验连线】--【校验连线】--【校验连线】--【校验连线】--【校验连线】--
        */
    },

    saveFlow: function() {
      //保存流程
      //当前选中工程项
      var curProjectItem = this.flowData.currentProjectDetail;
      if (curProjectItem.id) {
        this.saveCurrentFlowJson();
      } else {
        this.$notify({
          title: "提示",
          message: "请先选择工程！",
          type: "warning"
        });
      }
    },

    //同步流程json数据到服务端
    saveCurrentFlowJson: function() {
      var that = this;
      var curProjectItem = that.flowData.currentProjectDetail;
      var data = {};
      var nodes = that.flowData.nodes;
      var links = that.flowData.links;
      var compType = this.$store.state.project.systemComponents[0].children;
      let array1 = [];
      let array2 = [];

      compType.forEach(item => {
        item.children.forEach(aItem => {
          nodes.forEach(bItem => {
            // if (bItem.fileParse && bItem.fileParse.length > 0) {
            //   bItem.fileParse.splice(bItem.fileParse.length - 1, 1);
            // }
            if (
              aItem.name == bItem.name &&
              (item.name == "分类" ||
                item.name == "回归" ||
                item.name == "聚类" ||
                item.name == "时序模型")
            ) {
              array1.push(item.name);
              array2.push(bItem.name);
            }
          });
        });
      });

      // console.log(nodes);

      // (data["modelType"] = array1), (data["modelAlgorithm"] = array2);
      data["modelType"] = array1;
      data["modelAlgorithm"] = array2;
      data["style"] = that.flowData.contentStyle;
      data["nodes"] = nodes;
      data["links"] = links;

      // console.log(data)
      // return

      let formData = new FormData();
      formData.append("content", JSON.stringify(data));
      this.$.ajax({
        url: that.httpServer + "/api/project/" + curProjectItem.id,
        method: "post",
        data: formData,
        processData: false,
        contentType: false,
        beforeSend: function(xhr) {
          xhr.setRequestHeader("accessToken", localStorage.accessToken);
        },
        success: function(response) {
          // that.$notify({
          //   title: "提示",
          //   message: "保存成功",
          //   type: "success"
          // });
          setTimeout(() => {
            that.$nextTick(() => {
              that.$store.dispatch("getCurrentFlowJson", that.$route.query.id);
            });
          }, 1000);
        },
        error: function(response) {
          that.$store.commit("dealRequestError", response);
        }
      });
    },

    elbow: function(d) {
      //计算path d值
      var e = d.source,
        t = d.target;
      var n = (e.x + t.x) / 2,
        i = (e.y + t.y) / 2,
        r = 50,
        o = t.y - e.y;
      return (
        o > -100 && 100 > o && (r = Math.max(Math.abs(t.y - e.y) / 2, 30)),
        ["M", e.x, e.y, "Q", e.x, e.y + r, n, i, "T", t.x, t.y].join(" ")
      );
    }
  }
};
</script>
